Send a Text Message (SMS) - java

Sample code to send an SMS text message:

import com.google.gson.FieldNamingPolicy;

import com.google.gson.Gson;

import com.google.gson.GsonBuilder;

import com.google.gson.JsonArray;

import com.google.gson.JsonObject;

import com.google.gson.JsonPrimitive;

 

import java.io.BufferedReader;

import java.io.DataOutputStream;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

 

public class Default {

        public static String apiKey = "ApiKey";

 

        public static void main(String[] args) throws Exception {

               try {

                       sendSms();

               }

               catch(Exception ex) {

                       System.out.println(ex.getMessage());

               }

        }

 

         

        private static void sendSms() throws Exception {

 

               String url = "https://messagingapis.paylite.net/api/sms/send";

 

               Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();

 

               JsonObject jsonData = new JsonObject();

               jsonData.addProperty("ApiKey", apiKey);

               jsonData.addProperty("CountryCode",  "Country Code");

               jsonData.addProperty("ToNumber", "To Number");

               jsonData.addProperty("TextMessage", "Test Message");

 

               String postJsonData = gson.toJson(jsonData);

               System.out.println(postJsonData);

 

               postRequest(url, postJsonData);

        }

         

 

        private static void postRequest(String url, String postJsonData) throws Exception {

               URL obj = new URL(url);

               HttpURLConnection con = (HttpURLConnection) obj.openConnection();

 

               // Setting basic post request

               con.setRequestMethod("POST");

               con.setRequestProperty("Content-Type", "application/json");

 

               // Send post request

               con.setDoOutput(true);

               DataOutputStream wr = new DataOutputStream(con.getOutputStream());

               wr.writeBytes(postJsonData);

               wr.flush();

               wr.close();

 

               //Read output

               BufferedReader in =new BufferedReader(new InputStreamReader(con.getInputStream()));

               String output;

               StringBuffer response = new StringBuffer();

 

               while ((output = in.readLine()) != null) {

                       response.append(output);

               } in .close();

 

               // printing result from response

               System.out.println(response.toString());

        }

}